
package com.example.librarymanagement.exception;

import com.example.librarymanagement.result.Result;
import com.example.librarymanagement.result.ResultCode;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.util.NestedServletException;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局系统异常处理
 *
 * @author wx
 */
@RestControllerAdvice
@Slf4j
@Component
public class GlobalExceptionHandler {


    @ExceptionHandler(JsonProcessingException.class)
    public Result handleJsonProcessingException(JsonProcessingException e) {
        return Result.error(e.getMessage());
    }

    /**
     * 服务异常捕获
     *
     * @param e 捕获的异常
     */
    @ExceptionHandler(BizException.class)
    public Result handleBizException(BizException e) {
        if (e.getResultCode() != null) {
            return Result.custom(e.getResultCode());
        }
        return Result.error(e.getMessage());
    }

    /**
     * 数据验证异常捕获
     *
     * @param e 捕获的异常
     */
    @ExceptionHandler(NestedServletException.class)
    public Result handleNestedServletException(NestedServletException e) {
        return Result.error(ResultCode.USER_REQUEST_PARAM_ERROR.getCode(), e.getMessage(), null);
    }

    /**
     * 非法数据异常捕获
     *
     * @param e 捕获的异常
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public Result handler(IllegalArgumentException e) {
        log.error("Assert异常：----------------{}", e.getMessage());
        return Result.error(e.getMessage());
    }

    /**
     * 捕获验证异常，并提取异常信息封装返回参数
     *
     * @param e 捕获的异常
     */
    @ExceptionHandler(BindException.class)
    public Result handBindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError) -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return Result.error(ResultCode.USER_REQUEST_PARAM_ERROR.getCode(), ResultCode.USER_REQUEST_PARAM_ERROR.getMsg(), errorMap);
    }

}
